package cn.itcast.web.controller.cargo;

import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.DownloadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class OutProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    /*
      url:/cargo/contract/print.do
      作用： 进入货物列表导出页面
      参数：
    */
    @RequestMapping("/print")
    public String print(){
        return "cargo/print/contract-print";
    }



    /*
      url: /cargo/contract/printExcel.do
      作用： 货物导出（模板导出）
      参数：参数：inputDate 出货日期
      ResponseBody作用：返回普通字符串，返回json，下载
    */
    @RequestMapping("/printExcel")
    @ResponseBody
    public void printExcel(String inputDate) throws IOException {
        //1. 读取模板的输入流 , 读取webapp目录下的资源记得是使用ServletContext
        InputStream inputStream = session.getServletContext().getResourceAsStream("/make/xlsprint/tOUTPRODUCT.xlsx");
        //2. 使用模块的输入流创建一个工作薄
        Workbook workbook = new XSSFWorkbook(inputStream);
        //得到工作单
        Sheet sheet = workbook.getSheetAt(0);
        //3. 设置标题内容
        String title = inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表";
        //获取第0行
        Row row = sheet.getRow(0);
        //获取1个单元格
        Cell cell = row.getCell(1);
        //设置单元格的内容
        cell.setCellValue(title);

        //4. 提取第二行的样式出来存储到数组中，提供给后面的数据去使用
        CellStyle[] cellStyles = new CellStyle[8];
        //获取第二行
        row=  sheet.getRow(2);
        //遍历数组
        for (int i = 0; i < cellStyles.length; i++) {
            cell = row.getCell(i+1);
            cellStyles[i] =cell.getCellStyle();
        }

        //定义行索引
        int index = 2;
        //创建日期格式转化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //表格内容部分
        List<ContractProductVo> contractProductVoList = contractProductService.findByShipTime(inputDate, getLoginUser().getCompanyId());
        for (ContractProductVo contractProductVo : contractProductVoList) {
            row = sheet.createRow(index++);//每一个contractProductVo一行数据

            //客户
            if (contractProductVo.getCustomName()!=null){
                cell = row.createCell(1);
                cell.setCellStyle(cellStyles[0]);//设置单元格样式
                cell.setCellValue(contractProductVo.getCustomName());
            }

            //订单号
            if (contractProductVo.getContractNo()!=null){
                cell = row.createCell(2);
                cell.setCellStyle(cellStyles[1]);
                cell.setCellValue(contractProductVo.getContractNo());
            }
            //货号
            if (contractProductVo.getProductNo()!=null){
                cell = row.createCell(3);
                cell.setCellStyle(cellStyles[2]);
                cell.setCellValue(contractProductVo.getProductNo());
            }
            //数量
            if (contractProductVo.getCnumber()!=null){
                cell = row.createCell(4);
                cell.setCellStyle(cellStyles[3]);
                cell.setCellValue(contractProductVo.getCnumber());
            }
            //工厂
            if (contractProductVo.getFactoryName()!=null){
                cell = row.createCell(5);
                cell.setCellStyle(cellStyles[4]);
                cell.setCellValue(contractProductVo.getFactoryName());
            }
            //工厂交期
            if (contractProductVo.getDeliveryPeriod()!=null){
                cell = row.createCell(6);
                cell.setCellStyle(cellStyles[5]);
                cell.setCellValue(simpleDateFormat.format(contractProductVo.getDeliveryPeriod()));
            }
            //船期
            if (contractProductVo.getShipTime()!=null){
                cell = row.createCell(7);
                cell.setCellStyle(cellStyles[6]);
                cell.setCellValue(simpleDateFormat.format(contractProductVo.getShipTime()));
            }
            //贸易条款
            if (contractProductVo.getTradeTerms()!=null){
                cell = row.createCell(8);
                cell.setCellStyle(cellStyles[7]);
                cell.setCellValue(contractProductVo.getTradeTerms());
            }

        }


        /*//下载乱码的时候我们可以使用url编码
        String fileName = "出货表.xlsx";
        fileName = URLEncoder.encode(fileName,"UTF-8");
        //通知浏览器以附件下载的形式处理内容
        response.setHeader("content-disposition","attachment;filename="+fileName);

        //获取到浏览器的输出流
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);*/

        /*
            download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName)
                    byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
                    response：响应对象
                    returnName : 下载文件的名字
         */
        //字节数组输出流，该类的本质就是内部维护一个字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        new DownloadUtil().download(byteArrayOutputStream,response,"出货表.xlsx");
    }
/*
    @RequestMapping("/printExcel")
    @ResponseBody
    public void printExcel(String inputDate) throws IOException {
        //1、新建工作簿
        Workbook workbook = new XSSFWorkbook();

        //2、新建工作单
        Sheet sheet = workbook.createSheet("出货表");

        //3. 合并单元格
        *//*
        CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol)
               firstRow： 开始行
                lastRow:  结束行
                firstCol:  开始列
                lastCol:   结束列
         *//*
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        //4、设置列宽
        sheet.setColumnWidth(0,6*256);
        sheet.setColumnWidth(1,21*256);
        sheet.setColumnWidth(2,16*256);
        sheet.setColumnWidth(3,29*256);
        sheet.setColumnWidth(4,11*256);
        sheet.setColumnWidth(5,11*256);
        sheet.setColumnWidth(6,11*256);
        sheet.setColumnWidth(7,11*256);
        sheet.setColumnWidth(8,11*256);
        sheet.setColumnWidth(9,11*256);

        //5、表标题  显示文字的格式：2012年8月份出货表
        //inputDate  2015-01  2015年1
        //inputDate  2015-11  2015年11
        String title = inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表";
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(1);
        //设置单元格样式
        cell.setCellStyle(bigTitle(workbook));
        //设置内容
        cell.setCellValue(title);

        //表头部分
        String[] titles = {"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        row = sheet.createRow(1);
        for (int i = 0; i < titles.length; i++) {
            cell = row.createCell(i + 1);
            //设置单元格格式
            cell.setCellStyle(title(workbook));
            //设置内容
            cell.setCellValue(titles[i]);
        }

        //定义行索引
        int index = 2;
        //创建日期格式转化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //表格内容部分
        List<ContractProductVo> contractProductVoList = contractProductService.findByShipTime(inputDate, getLoginUser().getCompanyId());
        for (ContractProductVo contractProductVo : contractProductVoList) {
            row = sheet.createRow(index++);//每一个contractProductVo一行数据

            //客户
            if (contractProductVo.getCustomName()!=null){
                cell = row.createCell(1);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(contractProductVo.getCustomName());
            }

            //订单号
            if (contractProductVo.getContractNo()!=null){
                cell = row.createCell(2);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(contractProductVo.getContractNo());
            }
            //货号
            if (contractProductVo.getProductNo()!=null){
                cell = row.createCell(3);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(contractProductVo.getProductNo());
            }
            //数量
            if (contractProductVo.getCnumber()!=null){
                cell = row.createCell(4);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(contractProductVo.getCnumber());
            }
            //工厂
            if (contractProductVo.getFactoryName()!=null){
                cell = row.createCell(5);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(contractProductVo.getFactoryName());
            }
            //工厂交期
            if (contractProductVo.getDeliveryPeriod()!=null){
                cell = row.createCell(6);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(simpleDateFormat.format(contractProductVo.getDeliveryPeriod()));
            }
            //船期
            if (contractProductVo.getShipTime()!=null){
                cell = row.createCell(7);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(simpleDateFormat.format(contractProductVo.getShipTime()));
            }
            //贸易条款
            if (contractProductVo.getTradeTerms()!=null){
                cell = row.createCell(8);
                cell.setCellStyle(text(workbook));
                cell.setCellValue(contractProductVo.getTradeTerms());
            }

        }
            //download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName)
            //      byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
            //      response：响应对象
            //      returnName : 下载文件的名字

        //字节数组输出流，该类的本质就是内部维护一个字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        new DownloadUtil().download(byteArrayOutputStream,response,"出货表.xlsx");
    }*/

    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }

}
